/*
 * @Description: 
 * @Version: 1.0
 * @Author: truman
 * @Date: 2024-01-12 23:17:45
 * @LastEditors: Truman
 * @LastEditTime: 2024-03-26 13:48:04
 */
import { createApp } from 'vue'
import { createPinia, storeToRefs } from 'pinia'
import { ActionBar, ActionBarIcon, ActionBarButton, Divider, Popup, Overlay, Loading, Dialog, ContactCard, Form, AddressEdit, AddressList, Field, CellGroup, Cell, SwipeCell, Icon, Stepper, Card, Checkbox, CheckboxGroup, Button, Swipe, SwipeItem, PullRefresh, List, Tab, Tabs, SubmitBar, Toast, Skeleton, ActionSheet } from 'vant'
import { useStore } from '@/stores/index'

import App from './App.vue'
import router from './router'
import 'lib-flexible/flexible'
import wx from "weixin-js-sdk"

import './assets/main.css'
import './common/style/theme.css'
import 'vant/es/toast/style'
import { setLocal } from "@/common/js/utils";
import { getQueryString } from "./utils/common";
import { getWechatInfoByCode } from "@/service/home";
import { login } from "@/service/user";
import { showToast } from "vant";
const app = createApp(App)
app.provide('$wx', wx)

app.use(createPinia())
app.use(router)
app.use(ActionBarButton)
  .use(ActionBarIcon)
  .use(ActionBar)
  .use(Divider)
  .use(Popup)
  .use(Overlay)
  .use(Loading)
  .use(Dialog)
  .use(Toast)
  .use(ContactCard)
  .use(Form)
  .use(AddressEdit)
  .use(AddressList)
  .use(Field)
  .use(CellGroup)
  .use(Cell)
  .use(SwipeCell)
  .use(Icon)
  .use(Stepper)
  .use(Card)
  .use(Button)
  .use(Swipe)
  .use(SwipeItem)
  .use(PullRefresh)
  .use(List)
  .use(Tab)
  .use(Tabs)
  .use(SubmitBar)
  .use(Checkbox)
  .use(CheckboxGroup)
  .use(Skeleton)
  .use(ActionSheet)

// 全局过滤器
app.config.globalProperties.$filters = {
  prefix(url) {
    if (url && url.startsWith('http')) {
      return url
    } else {
      url = `http://backend-api-01.newbee.ltd${url}`
      return url
    }
  }
}

app.mount('#app')


// 路由守卫 start
router.beforeEach(async (to, from, next) => {
  const store = useStore();

  // 必须storeToRefs绑定否则拿不到最新值,因为解构破坏了响应式
  const { openid } = storeToRefs(store);
  const { VITE_HOST, VITE_APPID } = import.meta.env

  // 微信公众号appid-开发-基本配置中获取
  const appId = VITE_APPID

  // 获取code后再次跳转路径 window.location.href；例：www.baido.com/#/Home
  const toPath = VITE_HOST + '/#' + to.path
  // 核心步骤，获取code
  const hrefurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + encodeURIComponent(toPath) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  // 从地址栏获取code
  const code = getQueryString('code')
  // 有openid就放行，单纯为了获取openid，无需关心是否登录，绑定等
  const haveOpenidPass = ['/product', '/register']
  // 是否账号绑定了openid  
  const isBindAccount = async () => {
    const resGetInfo = await getByOpenid({ openid: openid.value })
    if (resGetInfo.code === 0) {
      if (resGetInfo.data) {
        // 已绑定
        store.setLoginInfo(resGetInfo.data)
        next()
      } else {
        // 未绑定 
        // 清空store用户信息
        store.setLoginInfo({
          user: {
            Uid: ''
          }
        })
        // contactUs 相当于注册，直接通过
        if (to.path == '/contactUs') {
          next()
        } else {
          next({
            path: '/register'
          })
        }
      }
    } else {
      // 请求失败，放行
      showToast(resGetInfo?.info || '请求失败！');
      next()
    }
  }

  console.log(openid);
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }

  if(store.loginInfo.openid){
    next()
  }
  /* 判断该路由是否需要登录权限 */
  if (to.matched.some(record => record.meta.requireAuth)) {
    if (openid.value) {
      if (haveOpenidPass.includes(to.path)) {
        next()
      } else {
        // 处理非prod环境下，控制台异常，报错无法跳转问题
        return isBindAccount()
      }
    } else { //openId不存在
      if (code) { //根据code获取openId
        const res = await getWechatInfoByCode(code)
        if (res) {
          store.setLoginInfo(res)
          if (res.password === '0') {
            next('/bind')
          } else {
            try {
              const data = await login({
                username: res.username,
                password: res.password,
              });

              setLocal("access_token", `Bearer ${data.access_token}`);
              setLocal("refresh_token", `Bearer ${data.refresh_token}`);

              showToast({
                message: "登录成功",
                className: "particulars-detail-popup",
              });
              to.query.isLogin = true
              next('/home')
            } catch (err) {
              console.log(err);
              showToast({
                message: "账号或密码错误！",
                className: "particulars-detail-popup",
              });
              return;
            }

          }
          // isBindAccount()
        } else {
          showToast(res?.info || '请求失败！');
        }
      } else {  //获取code
        window.location.replace(hrefurl)
      }
    }
  } else {
    next()
  }
})
// 路由守卫 end
